package at.ac.tuwien.swa.sparrow.desktop;

import at.ac.tuwien.swa.sparrow.common.Found$;
import at.ac.tuwien.swa.sparrow.common.Invalid$;
import at.ac.tuwien.swa.sparrow.common.TrackInfo;
import at.ac.tuwien.swa.sparrow.common.TrackResult;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.plaf.metal.MetalLookAndFeel;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Observable;
import java.util.Observer;

public class SWAzam {
	public static final String LABEL_TEXT = "Drop file on the icon";
	public static final String ERROR_MESSAGE = "Sorry, something went wrong...";

	public static void main(String... args) {
		if (args.length != 0) {
			SWAzamRuntime.init(args[0]);
		} else {
			SWAzamRuntime.init("swazam_install");
		}
		try {
			UIManager.installLookAndFeel("SeaGlass", "com.seaglasslookandfeel.SeaGlassLookAndFeel");
			UIManager.setLookAndFeel("com.seaglasslookandfeel.SeaGlassLookAndFeel");
		} catch (Exception e) {
			try {
				UIManager.setLookAndFeel(new MetalLookAndFeel());
			} catch (Exception e2) {
				//okay, then use default
			}
		}
		if (!SWAzamRuntime.getRuntime().isRegistered()) {
			createUserFrame();
			if (!SWAzamRuntime.getRuntime().isRegistered()) {
				return;
			}
		}
		final JFrame mainFrame = new JFrame("SWAzam");
		mainFrame.setSize(300, 350);
		mainFrame.setLocationRelativeTo(null);
		mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		mainFrame.setLayout(new BorderLayout());
		InputStream logoIn = SWAzam.class.getResourceAsStream("/music.png");
		BufferedImage myPicture = null;
		try {
			myPicture = ImageIO.read(logoIn);
		} catch (IOException e) {
			e.printStackTrace();
		}
		final ImageIcon swazamIcon = new ImageIcon(myPicture);
		JPanel topPanel = new JPanel();
		final JLabel resultLabel = new JLabel(LABEL_TEXT);
		topPanel.add(resultLabel);
		final JLabel picLabel = new JLabel(swazamIcon);
		topPanel.add(picLabel);
		picLabel.setToolTipText("drop file here");
		picLabel.setTransferHandler(new TransferHandler() {
			@Override
			@SuppressWarnings("unchecked")
			public boolean importData(TransferSupport support) {
				if (!support.isDrop() || !support.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
					return false;
				}
				Transferable t = support.getTransferable();
				try {
					java.util.List<File> data = (java.util.List<File>) t.getTransferData(DataFlavor.javaFileListFlavor);
					if (data.size() != 1)
						return false;
					SWAzamRuntime.getRuntime().identify(data.get(0));
				} catch (Exception e) {
					return false;
				}
				return true;
			}

			@Override
			public boolean canImport(TransferSupport support) {
				return support.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
			}
		});
		mainFrame.add(topPanel, BorderLayout.NORTH);
		final JProgressBar progressBar = new JProgressBar(0, 100);
		progressBar.setVisible(false);
		mainFrame.add(progressBar, BorderLayout.CENTER);
		final JPanel southPanel = new JPanel(new GridLayout(1, 2));
		final JButton recordButton = new JButton("Record");
		southPanel.add(recordButton);
		final JButton mySWAzamButton = new JButton("My SWAzam");
		mySWAzamButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (Desktop.isDesktopSupported()) {
					try {
						Desktop.getDesktop().browse(SWAzamRuntime.getRuntime().getMySWAzamURI());
					} catch (IOException e1) {
						JOptionPane.showMessageDialog(mainFrame, "Please visit " + SWAzamRuntime.getRuntime().getMySWAzamURI(), "MySWAzam", JOptionPane.INFORMATION_MESSAGE);
					}
				} else {
					JOptionPane.showMessageDialog(mainFrame, "Please visit " + SWAzamRuntime.getRuntime().getMySWAzamURI(), "MySWAzam", JOptionPane.INFORMATION_MESSAGE);
				}
			}
		});
		southPanel.add(mySWAzamButton);
		mainFrame.add(southPanel, BorderLayout.SOUTH);
		SWAzamRuntime.getRuntime().addObserver(new Observer() {
			@Override
			public void update(Observable o, final Object arg) {
				if (arg != null) {
					SwingUtilities.invokeLater(new Runnable() {
						@Override
						public void run() {
							progressBar.setVisible(true);
							resultLabel.setText("Working...");
							picLabel.setIcon(null);
							mySWAzamButton.setEnabled(false);
							recordButton.setEnabled(false);
							if (arg instanceof Integer) {
								progressBar.setValue((Integer) arg);
							} else if (arg instanceof TrackResult) {
								TrackResult r = (TrackResult) arg;
								if (r.state() == Found$.MODULE$) {
									TrackInfo info = ((TrackResult) arg).trackInfo();
									resultLabel.setText(info.artist() + " - " + info.title());
								} else if (r.state() == Invalid$.MODULE$) {
									resultLabel.setText("<html>Cannot Process Ticket:<br/>Please Check Your Credits.</html>");
								} else {
									resultLabel.setText("Sorry, we didn't find this song");
								}
							}
						}
					});
				} else {
					progressBar.setVisible(false);
					picLabel.setIcon(swazamIcon);
					mySWAzamButton.setEnabled(true);
					recordButton.setEnabled(true);
				}
			}
		});
		mainFrame.setVisible(true);
	}

	public static void createUserFrame() {
		final JDialog frame = new JDialog((Frame) null, "Login to SWAzam", true);
		frame.setResizable(false);
		frame.setSize(300, 350);
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		frame.setLayout(new BorderLayout());
		InputStream logoIn = SWAzam.class.getResourceAsStream("/music.png");
		BufferedImage myPicture = null;
		try {
			myPicture = ImageIO.read(logoIn);
		} catch (IOException e) {
			e.printStackTrace();
		}
		JLabel picLabel = new JLabel(new ImageIcon(myPicture));
		frame.add(picLabel, BorderLayout.NORTH);
		JPanel loginPanel = new JPanel();
		loginPanel.setLayout(new GridLayout(2, 1));
		final JTextField username = new JTextField(System.getProperty("user.name"));
		username.setToolTipText("Enter your username");
		final JPasswordField password = new JPasswordField("Password");
		loginPanel.add(username);
		loginPanel.add(password);
		frame.add(loginPanel, BorderLayout.CENTER);
		final JButton login = new JButton("Login");
		login.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				//TODO: check server
				SWAzamRuntime.getRuntime().setUser(username.getText(), new String(password.getPassword()));
				frame.dispose();
			}
		});
		frame.add(login, BorderLayout.SOUTH);
		frame.setVisible(true);
		frame.toFront();
	}
}
